<?php
namespace App\Http\Controllers\Dashboard;

use App\Events\Chat\NewMsg;
use App\Events\Chat\NewRoom;
use App\Events\Chat\NewRoomMsg;
use App\Models\ChatRoom;
use App\Models\ChatRoomMsg;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Http\Request;


class ChatController extends BaseController
{

    /**
     * 发言
     * @param Request $request
     * @return JsonResponse
     */
    public function roomMsg(Request $request) {
        $room_id = (int) $request->input('room_id', 0);

        if ($request->msg === '' || $request->msg === null) {
            return response()->json([
                'code' => 1,
                'msg' => '内容不能为空',
                'data' => null
            ]);
        }

        $user = $request->user();
        $msg = new ChatRoomMsg();
        $msg->room_id = $room_id;
        $msg->sender_id = $user->id;
        $msg->msg = $request->msg;

        if ($msg->save()) {
            $room = ChatRoom::updateOrCreate(
                ['room_id' =>  $msg->room_id],
                ['updated_at' => date("Y-m-d H:i:s")],
            );

            NewRoom::dispatch($room);
            NewRoomMsg::dispatch($msg);
            NewMsg::dispatch($msg);
            return response()->json([
                'code' => 0,
                'msg' => 'ok',
                'data' => null
            ]);
        }  else {
            return response()->json([
                'code' => 1,
                'msg' => '发送失败',
                'data' => null
            ]);
        }
    }

    /**
     * 加载房间历史消息
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function roomHistory(Request $request) {
        $pageSize = (int) $request->input('pageSize', 20);
        $room_id = (int) $request->input('room_id', 0);

        $timestamp = (int) $request->input('timestamp', time());
        $query = ChatRoomMsg::with('sender')
            ->where('created_at', '<=', date("Y-m-d H:i:s", $timestamp))
            ->where('room_id', $room_id)->orderByDesc('id');

        /* @var $pages \Illuminate\Contracts\Pagination\LengthAwarePaginator */
        $pages = $query->simplePaginate($pageSize);

        $data = [];
        foreach ($pages->items() as $v) {
            $data[] = [
                'id' => $v->id,
                'sender_id' => $v->sender_id,
                'sender' => $v->sender->name,
                'msg' => $v->msg,
                'created_at' => $v->created_at->format('Y/m/d H:i:s'),
            ];
        }

        $owner = $room_id > 0 ? User::find($room_id) : null;

        return response()->json([
            'code' => 0,
            'msg' => 'ok',
            'data' => [
                'title' => $owner ? $owner->name : ($room_id == 0 ? '公共大厅' : '未知'),
                'items' => $data,
            ]
        ]);
    }

    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function recentRoomList(Request $request) {
        $recent = ChatRoom::with('owner')
            ->where('room_id', '>', 0)
            ->orderByDesc('updated_at')
            ->limit(100)->get();

        foreach ($recent->reverse() as $v) {
            NewRoom::dispatch($v);
        }

        return response()->json([
            'code' => 0,
            'msg' => 'ok',
            'data' => null
        ]);
    }
}
